<template>
    <div>
        <Modal v-model="show" title="重置密码"
               :mask-closable="false" :closable="false">
            <Form ref="modalForm" :model="data"
                  :label-width="100" :rules="rules">
                <FormItem label="密码 " prop="password">
                    <Input v-model.trim="data.password" type="password" placeholder="密码"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" :disabled="loading" @click="cancel(false)">取消</Button>
                <Button type="primary" :loading="loading" @click="ok">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {mapActions} from 'vuex';

    export default {
        data() {
            return {
                loading: false,
                show: true,
                data: {
                    password: ''
                },
                rules: {
                    password: [
                        {required: true, message: '密码不能为空', trigger: 'blur'},
                        {
                            type: 'string',
                            min: 6,
                            max: 15,
                            pattern: /^[0-9A-Za-z]\w{5,15}$/,
                            message: '密码少于6位',
                            trigger: 'blur'
                        }
                    ]
                }
            };
        },
        props: {
            userId: {
                type: String,
                default: ''
            }
        },
        methods: {
            ...mapActions(['resetPassword']),
            cancel(reload = false) {
                this.$emit('cancel', 'reset', reload);
            },
            ok() {
                this.loading = true;
                this.$refs['modalForm'].validate((valid) => {
                    if (valid) {
                        this.resetPassword({
                            userId: this.userId,
                            password: this.data.password
                        }).then(res => {
                            if (res.code === '0000') {
                                this.$Message.success(this.$t('resetPasswordSuccess'));
                                this.cancel(true);
                                this.loading = false;
                            } else {
                                this.$Message.error(this.$t('resetPasswordFailed'));
                                this.cancel(true);
                                this.loading = false;
                            }
                        });
                    } else {
                        this.loading = false;
                    }
                });
            }
        }
    };
</script>